'''
@Author: your name
@Date: 2019-10-14 17:34:58
@LastEditTime : 2019-12-23 19:52:22
@LastEditors  : Please set LastEditors
@Description: In User Settings Edit
@FilePath: \IntelligentElderlyCare\server\service\buss_pub\role.py
'''
from ...service.welfare_institution.accommodation_process import CheckInStatus
from ...service.common import get_info, get_current_role_id, UserType, operation_result, get_current_organization_id
from ...pao_python.pao.data import process_db, dataframe_to_list
from ...service.mongo_bill_service import MongoBillFilter
from ...service.buss_pub.bill_manage import BillManageService, OperationType, TypeId, Status
from server.pao_python.pao.service.data.mongo_db import MongoService, MongoFilter, C, N, F, as_date
import pandas as pd
import uuid
from ...pao_python.pao.remote import JsonRpc2Error
import pandas as pd


class Role(MongoService):
    '''角色设置管理'''

    def __init__(self, db_addr, db_port, db_name, db_user, db_pwd, inital_password, session):
        self.db_addr = db_addr
        self.db_port = db_port
        self.db_name = db_name
        self.db_user = db_user
        self.db_pwd = db_pwd
        self.inital_password = inital_password
        self.session = session
        self.bill_manage_service = BillManageService(
            db_addr, db_port, db_name, db_user, db_pwd, inital_password, session)

    def get_role_user_list(self, org_list, condition, page, count):
        '''获取角色设置列表'''
        keys = ['id', 'name']
        values = self.get_value(condition, keys)
        _filter = MongoBillFilter()
        _filter.match_bill(
            (C('id') == values['id'])
            & (C('organization_id').inner(org_list))
        )\
            .inner_join_bill('PT_User', 'principal_account_id', 'id', 'principal_account_info')\
            .inner_join_bill('PT_User', 'role_of_account_id', 'id', 'role_of_account_info')\
            .inner_join_bill('PT_Role', 'role_id', 'id', 'role_info')\
            .match((C('role_info.name').like(values['name'])))\
            .project({'_id': 0, 'id': 1, 'principal_account_id': 1, 'role_of_account_id': 1, 'role_id': 1, 'principal_account': '$principal_account_info.name', 'role_of_account': '$role_of_account_info.name', 'name': '$role_info.name'})
        res = self.page_query(_filter, 'PT_Set_Role', page, count)
        return res

    def delete_role_user(self, condition):
        ids = []
        if isinstance(condition, str):
            ids.append({"id": condition})
        else:
            for id_str in condition:
                ids.append({"id": id_str})
        self.bill_manage_service.add_bill(OperationType.delete.value,
                                          TypeId.setRole.value, ids, 'PT_Set_Role')
        res = 'Success'
        return res

    def update_role_user(self, condition):
        '''新增/修改角色关联'''
        flag = OperationType.update.value if 'id' in condition.keys() else OperationType.add.value
        bill_id = self.bill_manage_service.add_bill(
            flag, TypeId.setRole.value, condition, 'PT_Set_Role')
        return operation_result(bill_id)

    def update_role(self, condition):
        '''新增/修改角色'''
        hasId = True if 'id' in condition.keys() else False
        role_id = condition['id'] if hasId else str(uuid.uuid1())
        flag = OperationType.update.value if hasId else OperationType.add.value
        _filter = MongoBillFilter()
        _filter.match_bill(C('id').inner(condition['ids']))\
               .project({'_id': 0})
        res = self.query(_filter, 'PT_Permission')
        # 权限表数据组织
        pf = pd.DataFrame(res)
        col_n = ['function', 'permission', 'remarks', 'is_allow_super_use']
        df = pd.DataFrame(pf, columns=col_n)
        df['organization_id'] = condition['organization_id']
        df['role_id'] = role_id
        df['remarks'] = str(condition['role_type'] + '_' + condition['name'])
        con = dataframe_to_list(df)
        if hasId:  # 编辑
            _filter_all = MongoBillFilter()
            _filter_all.match_bill(C('role_id') == role_id)\
                       .project({'_id': 0})
            res = self.query(_filter_all, 'PT_Permission')
            pf_res = pd.DataFrame(res)
            res_ids = dataframe_to_list(pd.DataFrame(pf_res, columns=['id']))
            bill_id = self.bill_manage_service.add_bill(
                OperationType.delete.value, TypeId.role.value, res_ids, 'PT_Permission')
        # 角色表数据组织
        role = {'id': role_id,
                'role_type': condition['role_type'], 'name': condition['name'], 'organization_id': condition['organization_id'],
                'comment': condition['comment'] if 'comment' in condition.keys() else ''
                }
        # 新增/编辑角色
        bill_id = self.bill_manage_service.add_bill(
            flag, TypeId.role.value, role, 'PT_Role')
        # 为角色新增权限
        permission_bill_id = self.bill_manage_service.add_bill(
            OperationType.add.value, TypeId.role.value, con, 'PT_Permission')
        return '保存成功' if bill_id and permission_bill_id else '保存失败'

    def get_role_type(self):
        role_id = get_current_role_id(self.session)
        _filter = MongoBillFilter()
        _filter.match_bill(C('id') == role_id)\
               .project({'_id': 0})
        res = self.query(_filter, 'PT_Role')
        role_type_res = res[0]['role_type']
        role_type = ['平台', '福利院', '幸福院', '服务商',
                     '民政局'] if role_type_res == '平台' else [role_type_res]
        return role_type

    def delete_role(self, condition):
        ids = []
        if isinstance(condition, str):
            ids.append(condition)
        else:
            ids = condition
        _filter = MongoBillFilter()
        _filter.match_bill(C('role_id').inner(ids))\
               .project({'_id': 0})
        res = self.query(_filter, 'PT_Set_Role')
        if len(res):
            raise JsonRpc2Error(-36201, '该角色已经关联管理员账号，无法删除')
        delete_data = []
        for x in ids:
            delete_data.append({'id': x})
        bill_id = self.bill_manage_service.add_bill(OperationType.delete.value,
                                                    TypeId.role.value, delete_data, 'PT_Role')
        return bill_id

    def get_role_all_list(self, org_list, condition, page, count):
        '''获取角色列表'''
        keys = ['id', 'name', 'function', 'permission']
        values = self.get_value(condition, keys)
        _filter = MongoBillFilter()
        if 'is_platform' in condition.keys():
            role_id = get_current_role_id(self.session)
            _filter_cur = MongoBillFilter()
            _filter_cur.match_bill(C('id') == role_id)\
                .project({'_id': 0})
            res = self.query(_filter_cur, 'PT_Role')
            cur_type = res[0]['role_type']
            _filter.match_bill(
                (((C('is_platform') == '平台') & (C('role_type') == cur_type))) | (C('organization_id').inner(org_list)))
        else:
            _filter.match_bill(C('organization_id').inner(org_list))
        _filter.match((C('id') == values['id'])
                      & (C('name').like(values['name']))
                      )\
            .inner_join_bill('PT_User', 'organization_id', 'id', 'org')\
            .lookup_bill('PT_Permission', 'id', 'role_id', 'permiss_list')\
            .project({'_id': 0, 'user._id': 0, 'permiss_list._id': 0, 'org._id': 0})
        res = self.page_query(_filter, 'PT_Role', page, count)
        return res

    def get_permiss_list(self, org_list, condition, page, count):
        _filter = MongoBillFilter()
        role_id = condition['role_id'] if 'role_id' in condition.keys(
        ) else get_current_role_id(self.session)
        _filter.match_bill(C('role_id') == role_id)\
            .project({'_id': 0})
        res = self.page_query(_filter, 'PT_Permission', page, count)
        return res

    def get_role_single(self, condition):
        _filter = MongoBillFilter()
        # 当前账号角色和组织id
        values = self.get_value(
            {
                'cur_role_id': get_current_role_id(self.session),
                'cur_organization_id': get_current_organization_id(self.session)
            }, ['cur_role_id', 'cur_organization_id'])
        _filter.match_bill(C('role_id') == condition['id'])\
               .lookup_bill('PT_Permission', 'function', 'function', 'permission_list')\
               .add_fields({'org_permiss_list': self.ao.array_filter("$permission_list", "aa", ((F('$aa.role_id') == values['cur_role_id']) & (F('$aa.permission') == (F('permission')))).f)})\
            .match_bill(
            C('permission_list.role_id') == values['cur_role_id'])\
            .inner_join_bill('PT_Role', 'role_id', 'id', 'role')\
            .project({'_id': 0, 'permission_list': 0, 'org_permiss_list._id': 0, 'role._id': 0})
        res = self.query(_filter, 'PT_Permission')
        return res
